﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DSkin.Controls;
using DSkin.Forms;
using VectorDraw.Professional.vdCollections;
using VectorDraw.Professional.vdCommandLine;
using VectorDraw.Professional.vdObjects;
using VectorDraw.Professional.vdPrimaries;

namespace ZhCAD
{
    public partial class MainForm :  Skin_VS_Blue, IMainform
    {
        private Childform _childform;
        private bool _isGis;
        private ToolbarStandard _standard;
        public bool MDisplayPolarCoord = true;

        private bool _isOpenXieTong = false;





        public MainForm()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            //IsLayeredWindowForm = false;
            CommandLine.LoadCommands(Path.GetDirectoryName(Application.ExecutablePath), "Commands.txt");
            CommandLine.CommandExecute += CommandLine_CommandExecute;
            CommandLine.UserText.KeyDown += UserText_KeyDown;
            TabDocuments.SelectedIndex = -1;
        }

        public vdPropertyGrid.vdPropertyGrid Vdgrid => vdPropertyGrid1;
        public void ShowProgress(object sender, long pre, string jobdesc)
        {
            toolStripLabjob.Visible = pre != 0;
            toolStripProgressBar1.Visible = pre != 0;
                toolStripLabjob.Text = jobdesc;
                toolStripProgressBar1.Value = (int)pre;

            Application.DoEvents();
            //throw new NotImplementedException();
        }

        public ToolStripLabel CoordDisplay => CoordDisplaylab1;

        public Childform CurrentChildform
        {
            get => _childform;
            set
            {
                _childform = value;
                if (_childform != null)
                    ActiveChildform(_childform);
                else
                    RemoveHandleObj();
            }
        }

        public  vdCommandLine CommandLine
        {
            get { return vdCommandLine1; }
            set { }
        }

        public  void UpdateFileTree(FileTree fileTree)
        {
            if (fileTree == null)
            {
                if (trvFiletree.Tag != null) fileTree = (FileTree)trvFiletree.Tag;
            }
            else
            {
                trvFiletree.Tag = fileTree;
            }
            if (fileTree == null) return;

                var doc = CurrentChildform.Document;
            trvFiletree.Nodes.Clear();
            foreach (string filename in fileTree.GetFiles())
            {
                var filenode = new DSkinTreeViewNode
                {
                    Text = filename,
                    CheckState = CheckState.Checked
                };
                trvFiletree.Nodes.Add(filenode);
                foreach (var layer in fileTree.GetLayers(filename))
                {
                    var list = fileTree.GetFeaturesByLayer(filename, layer);
                    var laynode = new DSkinTreeViewNode
                    {
                        Text = layer,
                        Tag = list,
                        CheckState =
                            doc.Layers.FindName(layer).On & !doc.Layers.FindName(layer).Frozen
                                ? CheckState.Checked
                                : CheckState.Unchecked,
                        Icon = imageList1.Images[ColorBy(fileTree.GetLayer(layer).Color)]
                    };
                    filenode.Nodes.Add(laynode);
                    
                    if (!_isGis)
                    {//CASS
                        foreach (var cass in fileTree.GetCassByLayer(filename, layer))
                        {
                            List<int> ids = FileTree.GetIdsByCass(list, cass);
                            var node = new DSkinTreeViewNode
                            {
                                Text = $"{cass}[{ids.Count()}]".PadRight(16) + DocHelper.GetCassDesc(cass),
                                Tag = ids,
                                CheckState = laynode.CheckState,
                                Icon = imageList1.Images[ColorBy(fileTree.GetLayer(layer).Color, false)]
                            };
                            laynode.Nodes.Add(node);
                        }


                        //var gEnumerable = list.GroupBy(x => x.Cass, x => x.Id);
                        //foreach (var grp in gEnumerable)
                        //{
                        //    var node = new DSkinTreeViewNode
                        //    {
                        //        Text = $"{grp.Key}[{grp.Count()}]".PadRight(16) + DocHelper.GetCassDesc(grp.Key),
                        //        Tag = grp.ToList(),
                        //        CheckState = laynode.CheckState,
                        //        Icon = imageList1.Images[ColorBy(fileTree.GetLayer(layer).Color, false)]
                        //    };
                        //    laynode.Nodes.Add(node);
                        //}
                    }
                    else
                    {

                        foreach (var shapetype in fileTree.GetShapeTypeByLayer(filename,layer))
                        {
                            List<int> ids = FileTree.GetIdsByShapeType(list, shapetype);
                            var node = new DSkinTreeViewNode
                            {
                                Text = shapetype + $"[{ids.Count()}]",
                                Tag = ids,
                                CheckState = laynode.CheckState,
                                Icon = imageList1.Images[ColorBy(fileTree.GetLayer(layer).Color, false)]
                            };
                            laynode.Nodes.Add(node);
                        }

                        //var gEnumerable = list.GroupBy(x => x.EntType, x => x.Id);
                        //foreach (var grp in gEnumerable)
                        //{
                        //    var node = new DSkinTreeViewNode
                        //    {
                        //        Text = grp.Key + $"[{grp.Count()}]",
                        //        Tag = grp.ToList(),
                        //        CheckState = laynode.CheckState,
                        //        Icon = imageList1.Images[ColorBy(fileTree.GetLayer(layer).Color, false)]
                        //    };
                        //    laynode.Nodes.Add(node);
                        //}
                    }
                    filenode.Open();
                }
            }
           // SortTreenodes();
        }

        public  void SelectObject(object obj)
        {
            Vdgrid.SelectedObject = obj;
        }

        public  void ShowCoordinate(string text)
        {
            CoordDisplay.Text = text;
        }

        public  void CommandEx(string cmd)
        {
            CommandLine.ExecuteCommand(cmd);
            ;
        }

        public bool IsService { get; set; }

        private void UserText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
                CommandEx(CommandLine.UserTextString.Trim());
        }

        private void CommandLine_CommandExecute(string commandname, bool isDefaultImplemented, ref bool success)
        {
            switch (commandname.ToLower())
            {
                case "open":
                    success = true;
                    var openFileNameDlg = DocHelper.GetOpenFileNameDlg();
                    if (openFileNameDlg != null)
                        AddTab(new Childform(openFileNameDlg, this));
                    break;
                case "new":
                    AddTab(new Childform(new List<string>().ToArray(), this));
                    success = true;
                    break;
                case "pan":
                    if (_childform == null)
                        return;
                    _childform.vdScrollableControl1.BaseControl.ActiveDocument.CommandAction.Pan();
                    break;
            }
        }

        private void AddTab(Childform frm)
        {
            //frm.MdiParent = this;
            frm.TopLevel = false;
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.Dock = DockStyle.Fill;
            frm.Show();
            var tb = new DSkinTabPage();
            tb.Controls.Add(frm);
            tb.Text = frm.Text;
            tb.Name = frm.Name;
            TabDocuments.TabPages.Add(tb);
            TabDocuments.SelectTab(tb);
            CurrentChildform = frm;
        }

        private string ColorBy(Color layerColor, bool isrec = true)
        {
            var colorkey = (isrec ? "1" : "0") + "-" + layerColor;
            if (!imageList1.Images.ContainsKey(colorkey))
                imageList1.Images.Add(colorkey, MyCommon.Createimg(layerColor, imageList1.ImageSize, isrec));
            return colorkey;
        }


        private void SortTreenodes()
        {
            if (trvFiletree.Nodes.Count == 0) return;

            foreach (DSkinTreeViewNode filetreeNode in trvFiletree.Nodes)
            {
                foreach (DSkinTreeViewNode layernode in filetreeNode.Nodes)
                    SortNodes(layernode);
                SortNodes(filetreeNode);
            }
            trvFiletree.ExpandAll();
            trvFiletree.LayoutContent();
            trvFiletree.CollapseAll();
            foreach (DSkinTreeViewNode filetreeNode in trvFiletree.Nodes)
            {
                filetreeNode.Open();
                foreach (DSkinTreeViewNode dSkinTreeViewNode in filetreeNode.Nodes)
                    dSkinTreeViewNode.Close();
            }

            //trvFiletree.CollapseAll();
        }

        private void SortNodes(DSkinTreeViewNode parenNode)
        {
            var sortedDictionary = new SortedDictionary<string, DSkinTreeViewNode>();
            foreach (DSkinTreeViewNode node in parenNode.Nodes)
                sortedDictionary.Add(node.Text, node);
            parenNode.Nodes.Clear();
            parenNode.Nodes.AddRange(sortedDictionary.Values.ToArray());
        }

        private void ShowFeatures(List<int> ids, vdFigure.VisibilityEnum visibled)
        {
            var doc = (vdDocument) CommandLine.GetSelectedDocument();
            if (doc != null)
            {
                foreach (var id in ids)
                    doc.Model.Entities.FindFromId(id).visibility = visibled;
                doc.Redraw(false);
            }
        }

        private void trvFiletree_NodeMouseDoubleClick(object sender, DSkinTreeViewNodeClickEventArgs e)
        {
            if (e.Item.Level != 2) return;
            {
                var doc = _childform.Document;
                _childform.BshowProperty = false;
                if (doc != null)
                {
                    var selection = doc.Selections[0];
                    selection.RemoveAll();
                    var ids = (List<int>) e.Item.Tag;
                    foreach (var id in ids)
                        selection.AddItem(doc.Model.Entities.FindFromId(id), false,
                            vdSelection.AddItemCheck.RemoveInVisibleEntities, true);
                    if (selection.Count != 0)
                    {
                        selection.ShowGrips(true);
                        var extbox = selection.GetBoundingBox();
                        doc.ZoomWindow(extbox.LowerRight, extbox.UpperLeft);
                        doc.ZoomScale(1.25);
                        doc.Redraw(false);
                        Vdgrid.SelectedObject = selection;
                    }
                }
                _childform.BshowProperty = true;
            }
        }

        private void trvFiletree_NodeCheckStateChanged(object sender, DSkinTreeViewEventArgs e)
        {
            switch (e.Item.Level)
            {
                case 0: //file
                case 1: //layer
                    if (e.Item.CheckState != CheckState.Indeterminate)
                        foreach (DSkinTreeViewNode node in e.Item.Nodes)
                            node.CheckState = e.Item.CheckState;
                    break;
                case 2: //featlist
                    ShowFeatures((List<int>) e.Item.Tag,
                        e.Item.CheckState == CheckState.Checked
                            ? vdFigure.VisibilityEnum.Visible
                            : vdFigure.VisibilityEnum.Invisible);
                    break;
            }
        }

        private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CommandEx("new");
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CommandEx("open");
        }

        private void RemoveHandleObj()
        {
            CommandLine.SelectDocument(null);
            Vdgrid.SelectedObject = null;
            trvFiletree.Nodes.Clear();
            SetToolbar();
        }

        private void ActiveChildform(Childform frm)
        {
            CommandLine.SelectDocument(frm.Document);
            var selection = frm.Document.GetGripSelection();
            if (selection.Count == 0)
                Vdgrid.SelectedObject = frm.Document;
            else
                Vdgrid.SelectedObject = selection;

            UpdateFileTree(frm.Filelist);
            SetToolbar();
        }

        private void SetToolbar()
        {
            if (_standard != null && _childform != null)
                _standard.DocForm = _childform;
        }

        private void 标准ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ToolStrip tool=new DSkinToolStrip();
            //tool.Items.Add(new ToolStripControlHost(new vdLayersCombo()));
            if (标准ToolStripMenuItem.Checked)
            {
                if (_standard == null)
                {
                    _standard = new ToolbarStandard();
                    toolStripContainer1.TopToolStripPanel.Controls.Add(_standard);
                }
                SetToolbar();
            }
            else
            {
                _standard.Parent.Controls.Remove(_standard);
                _standard.Dispose();
                _standard = null;
            }
        }

        private void btnGIS_Click(object sender, EventArgs e)
        {
            SwithGis(true);
        }

        private void btnNarmal_Click(object sender, EventArgs e)
        {
            SwithGis(false);
        }

        private void SwithGis(bool gis)
        {
            _isGis = gis;
            btnGIS.Checked = _isGis;
            btnNarmal.Checked = !_isGis;
            UpdateFileTree(null);
        }

        private void TabDocuments_Selected(object sender, TabControlEventArgs e)
        {
            CurrentChildform = e.TabPageIndex == -1 ? null : (Childform) e.TabPage.Controls[0];
        }

        private void 做为服务端ToolStripMenuItem_Click(object sender, EventArgs e)
        {
      
                IsService = ((ToolStripMenuItem)sender).Checked;
                mnuOpenRemoteDOC.Enabled = !IsService;
            if (IsService)
            {
                _isOpenXieTong = true;
            }


        }

        private void mnuOpenRemoteDOC_Click(object sender, EventArgs e)
        {
            IsService = false;
            _isOpenXieTong = true;
        }
    }
}